import subprocess
import requests
import folium
from geopy.geocoders import Nominatim

def get_public_ip():
    """
    使用 curl 命令获取公网 IP 地址
    """
    try:
        # 执行 curl 命令
        result = subprocess.run(['curl', 'ifconfig.me'], capture_output=True, text=True, check=True)
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        print(f"执行 curl 命令时出错: {e}")
        return None

def get_location_from_ip(api_token, ip):
    """
    通过 IP 地址获取经纬度和城市信息
    """
    headers = {"Authorization": f"Bearer {api_token}"}
    url = f"https://ipinfo.io/{ip}/json"
    response = requests.get(url, headers=headers)
    data = response.json()

    location = {
        "ip": data.get("ip"),
        "city": data.get("city"),
        "region": data.get("region"),
        "country": data.get("country"),
        "latitude": float(data.get("loc").split(",")[0]),  # 纬度
        "longitude": float(data.get("loc").split(",")[1]),  # 经度
    }
    return location

def create_map(latitude, longitude, city):
    """
    创建交互式地图并标记位置
    """
    # 创建地图中心（经纬度 + 缩放级别）
    map_obj = folium.Map(location=[latitude, longitude], zoom_start=13)

    # 添加标记
    folium.Marker(
        location=[latitude, longitude],
        popup=f"<h4>{city}</h4>",  # 弹窗显示城市名
        icon=folium.Icon(icon="cloud", color="blue")  # 自定义图标
    ).add_to(map_obj)

    # 保存为 HTML 文件
    map_obj.save("location_map.html")
    print(f"地图已生成：location_map.html")

if __name__ == "__main__":
    # 替换为你的 IPinfo API Token
    API_TOKEN = "553b53f530762f"

    # 获取公网 IP 地址
    public_ip = get_public_ip()
    if public_ip:
        try:
            # 获取位置信息
            location = get_location_from_ip(API_TOKEN, public_ip)
            print(f"检测到位置：{location['city']}, {location['country']}")

            # 生成地图
            create_map(
                latitude=location["latitude"],
                longitude=location["longitude"],
                city=location["city"]
            )

            # 可选：反解析地址（需要额外库）
            geolocator = Nominatim(user_agent="my_app")
            address = geolocator.reverse(f"{location['latitude']}, {location['longitude']}")
            print(f"详细地址：{address.address}")

        except Exception as e:
            print(f"错误：{str(e)}")
            print("请检查 API 密钥是否正确，或网络是否正常。")
    else:
        print("无法获取公网 IP 地址。")